package com.hys.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hys.dao.TaskMapper;
import com.hys.dto.TaskDTO;
import com.hys.entity.CoopAudit;
import com.hys.entity.Task;
import com.hys.entity.User;
import com.hys.enums.ApprovalStatusVOEnum;
import com.hys.enums.AuditStatusEnum;
import com.hys.service.CoopAuditService;
import com.hys.service.TaskService;
import com.hys.service.UserService;
import com.hys.util.BeanUtil;
import com.hys.vo.AuditUserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class TaskServiceImpl extends ServiceImpl<TaskMapper, Task> implements TaskService {

    @Autowired
    private UserService userService;

    @Autowired
    private CoopAuditService coopAuditService;

    @Autowired
    private static final Integer END_ORDER_NUM = 0;

    @Autowired
    private static final Integer BEGIN_ORDER_NUM = 1;

    /**
     * 获取任务列表
     * @param id
     * @param batchNo
     * @return
     */
    public List<AuditUserVO> getList(Integer id, String taskName ,String batchNo) {
        // 任务信息
        List<TaskDTO> defaultTaskInfo = getDefaultTaskInfo(taskName);
        // 查询当前审批信息
        List<CoopAudit> list = coopAuditService.list(id, batchNo);
        // 转换结果
        return convertToAuUserVO(defaultTaskInfo, list);
    }

    /**
     * 转换成结果
     * @param defaultTaskInfo
     * @param list
     * @return
     */
    private List<AuditUserVO> convertToAuUserVO(List<TaskDTO> defaultTaskInfo, List<CoopAudit> list) {

        // 结果
        List<AuditUserVO> result = defaultTaskInfo.stream().map( taskDTO -> {
            AuditUserVO auditUserVO = new AuditUserVO();
            auditUserVO.setOrderNum(taskDTO.getOrderNum());
            auditUserVO.setStatus(ApprovalStatusVOEnum.NOT_PASSED.getCode());
            auditUserVO.setUserName(taskDTO.getUserNames());
            return auditUserVO;
        }).collect(Collectors.toList());
        Collections.reverse(result);
        // 未审批
        if(CollectionUtil.isEmpty(list)){
            return result;
        }
        // 进行状态的覆盖
        Map<Integer, CoopAudit> orderNumMap = list.stream()
                .collect(Collectors.toMap(CoopAudit::getOrderNumber, Function.identity()));
        for (int i = 0; i < result.size(); i++) {

            AuditUserVO auditUserVO = result.get(i);
            Integer orderNum = auditUserVO.getOrderNum();
            CoopAudit coopAudit = orderNumMap.get(orderNum);
            if( coopAudit == null){
                continue;
            }else{
                if(coopAudit.getStatus().equals(AuditStatusEnum.PASSED.getCode())){
                    auditUserVO.setStatus(ApprovalStatusVOEnum.PASSED.getCode());
                }else{
                    auditUserVO.setStatus(ApprovalStatusVOEnum.REJECTED.getCode());
                }
            }
        }
        return result;
    }

    /**
     * 获取默认的任务信息
     * @return
     */
    private List<TaskDTO> getDefaultTaskInfo(String taskName) {
        // 查询默认的用户形式
        QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Task::getName, taskName).orderByDesc(Task::getOrderNum);
        List<Task> list = list(queryWrapper);
        List<TaskDTO> resultList = new ArrayList<>();

        // 查询用户信息
        for (int i = 0; i < list.size(); i++) {
            Task task = list.get(i);
            TaskDTO taskDTO = BeanUtil.transform(TaskDTO.class, task);
            String candidateUsers = task.getCandidateUsers();
            List<Long> userIds = Arrays.stream(candidateUsers
                    .split(","))
                    .map(userId -> Long.valueOf(userId)).collect(Collectors.toList());
            // 查询关联用户姓名
            String userNames = userService.listByIds(userIds).stream().map(User::getName).collect(Collectors.joining(","));
            // 用户名称
            taskDTO.setUserNames(userNames);
            resultList.add(taskDTO);
        }
        return resultList;
    }


    @Override
    public boolean isFirstTask(Task task) {
        Integer orderNum = task.getOrderNum();
        return BEGIN_ORDER_NUM.equals(orderNum);
    }

    @Override
    public List<Task> listTasksByName(String taskName) {

        QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Task::getName, taskName);
        return list(queryWrapper);
    }

    @Override
    public Task getTaskByNameNumber(String taskName, Integer orderNum) {

        QueryWrapper<Task> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(Task::getName, taskName).eq(Task::getOrderNum, orderNum);
        return getOne(queryWrapper);
    }

    @Override
    public Task getNextTask(Task currentTask) {
        Task taskByNameNumber = getTaskByNameNumber(currentTask.getName(), currentTask.getNextOrderNum());
        return taskByNameNumber;
    }

    @Override
    public boolean isLastTask(Task task) {
        return END_ORDER_NUM.equals(task.getNextOrderNum());
    }
}
